package com.example.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dto.ApiResponse;
import com.example.dto.QuestionRequest;
import com.example.entity.Question;
import com.example.mapper.QuestionMapper;
import com.example.service.QuestionService;
import com.example.service.UserService;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private UserService userService;
    
    @Override
    @Transactional
    public ApiResponse<?> addQuestion(QuestionRequest questionRequest) {
        // 检查试题类型
        if (!isValidQuestionType(questionRequest.getType())) {
            return ApiResponse.error("无效的试题类型，支持的类型包括：SINGLE_CHOICE, MULTIPLE_CHOICE, TRUE_FALSE, FILL_BLANK, SHORT_ANSWER");
        }
        
        // 验证选择题必须有选项
        if (("MULTIPLE_CHOICE".equals(questionRequest.getType()) || 
             "SINGLE_CHOICE".equals(questionRequest.getType())) && 
            (questionRequest.getOptions() == null || questionRequest.getOptions().isEmpty())) {
            return ApiResponse.error("选择题必须包含选项");
        }
        
        // 验证单选题只能有一个答案
        if ("SINGLE_CHOICE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers() == null || questionRequest.getAnswers().size() != 1)) {
            return ApiResponse.error("单选题只能有一个答案");
        }
        
        // 验证多选题必须有多个答案
        if ("MULTIPLE_CHOICE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers() == null || questionRequest.getAnswers().size() < 2)) {
            return ApiResponse.error("多选题必须至少有两个答案");
        }
        
        // 判断题答案格式验证
        if ("TRUE_FALSE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers().size() != 1 || 
            (!questionRequest.getAnswers().get(0).equals("true") && !questionRequest.getAnswers().get(0).equals("false")))) {
            return ApiResponse.error("判断题答案必须是单个'true'或'false'");
        }
        
        // 创建试题实体
        Question question = new Question();
        question.setContent(questionRequest.getContent());
        question.setType(questionRequest.getType());
        question.setDifficulty(questionRequest.getDifficulty());
        question.setScore(questionRequest.getScore());
        question.setOptions(questionRequest.getOptions());
        question.setAnswers(questionRequest.getAnswers());
        question.setExplanation(questionRequest.getExplanation());
        question.setKnowledgePoint(questionRequest.getKnowledgePoint());
        
        // 设置创建者ID
        Long currentUserId = userService.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("用户未登录或会话已过期");
        }
        question.setCreatorId(currentUserId);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        question.setCreateTime(now);
        question.setUpdateTime(now);
        
        // 保存试题
        questionMapper.insert(question);
        
        return ApiResponse.success("试题添加成功", question);
    }

    @Override
    @Transactional
    public ApiResponse<?> updateQuestion(Long id, QuestionRequest questionRequest) {
        // 检查试题是否存在
        Question existingQuestion = questionMapper.selectById(id);
        if (existingQuestion == null) {
            return ApiResponse.error("试题不存在");
        }
        
        // 检查是否有权限修改
        Long currentUserId = userService.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("用户未登录或会话已过期");
        }
        
        // 只有创建者或管理员可以修改试题
        // if (!existingQuestion.getCreatorId().equals(currentUserId) && !isAdmin()) {
        //     return ApiResponse.error("您没有权限修改此试题");
        // }
        
        // 验证试题类型
        if (!isValidQuestionType(questionRequest.getType())) {
            return ApiResponse.error("无效的试题类型，支持的类型包括：SINGLE_CHOICE, MULTIPLE_CHOICE, TRUE_FALSE, FILL_BLANK, SHORT_ANSWER");
        }
        
        // 验证选择题必须有选项
        if (("MULTIPLE_CHOICE".equals(questionRequest.getType()) || 
             "SINGLE_CHOICE".equals(questionRequest.getType())) && 
            (questionRequest.getOptions() == null || questionRequest.getOptions().isEmpty())) {
            return ApiResponse.error("选择题必须包含选项");
        }
        
        // 验证单选题只能有一个答案
        if ("SINGLE_CHOICE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers() == null || questionRequest.getAnswers().size() != 1)) {
            return ApiResponse.error("单选题只能有一个答案");
        }
        
        // 验证多选题必须有多个答案
        if ("MULTIPLE_CHOICE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers() == null || questionRequest.getAnswers().size() < 2)) {
            return ApiResponse.error("多选题必须至少有两个答案");
        }
        
        // 判断题答案格式验证
        if ("TRUE_FALSE".equals(questionRequest.getType()) && 
            (questionRequest.getAnswers().size() != 1 || 
            (!questionRequest.getAnswers().get(0).equals("true") && !questionRequest.getAnswers().get(0).equals("false")))) {
            return ApiResponse.error("判断题答案必须是单个'true'或'false'");
        }
        
        // 更新试题属性
        existingQuestion.setContent(questionRequest.getContent());
        existingQuestion.setType(questionRequest.getType());
        existingQuestion.setDifficulty(questionRequest.getDifficulty());
        existingQuestion.setScore(questionRequest.getScore());
        existingQuestion.setOptions(questionRequest.getOptions());
        existingQuestion.setAnswers(questionRequest.getAnswers());
        existingQuestion.setExplanation(questionRequest.getExplanation());
        existingQuestion.setKnowledgePoint(questionRequest.getKnowledgePoint());
        existingQuestion.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        questionMapper.updateById(existingQuestion);
        
        return ApiResponse.success("试题更新成功", existingQuestion);
    }

    @Override
    @Transactional
    public ApiResponse<?> deleteQuestion(Long id) {
        // 检查试题是否存在
        Question existingQuestion = questionMapper.selectById(id);
        if (existingQuestion == null) {
            return ApiResponse.error("试题不存在");
        }
        
        // 检查是否有权限删除
        Long currentUserId = userService.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("用户未登录或会话已过期");
        }
        
        // 只有创建者或管理员可以删除试题
        // if (!existingQuestion.getCreatorId().equals(currentUserId) && !isAdmin()) {
        //     return ApiResponse.error("您没有权限删除此试题");
        // }
        
        // 删除试题
        questionMapper.deleteById(id);
        
        return ApiResponse.success("试题删除成功", null);
    }

    @Override
    public Question getQuestionById(Long id) {
        return questionMapper.selectById(id);
    }

    @Override
    public List<Question> getAllQuestions() {
        return questionMapper.selectList(null);
    }

    @Override
    public IPage<Question> getQuestionsByPage(int page, int size, String type, Integer difficulty, String knowledgePoint) {
        // 参数验证
        if (page < 1) {
            page = 1;
        }
        if (size < 1 || size > 100) {
            size = 10;
        }
        
        // 创建分页对象
        Page<Question> pageParam = new Page<>(page, size);
        
        // 获取总记录数
        Long total = questionMapper.countQuestions(type, difficulty, knowledgePoint);
        pageParam.setTotal(total);
        
        // 执行分页查询
        IPage<Question> result = questionMapper.findQuestionsByCondition(pageParam, type, difficulty, knowledgePoint);
        
        // 处理选择题的选项和答案
        if (result != null && result.getRecords() != null) {
            for (Question question : result.getRecords()) {
                if (("MULTIPLE_CHOICE".equals(question.getType()) || 
                     "SINGLE_CHOICE".equals(question.getType())) && 
                    (question.getOptions() == null || question.getAnswers() == null)) {
                    // 如果是选择题但没有选项或答案，设置默认值
                    if (question.getOptions() == null) {
                        question.setOptions(java.util.Arrays.asList("选项A", "选项B", "选项C", "选项D"));
                    }
                    if (question.getAnswers() == null) {
                        if ("SINGLE_CHOICE".equals(question.getType())) {
                            question.setAnswers(java.util.Arrays.asList("A"));
                        } else {
                            question.setAnswers(java.util.Arrays.asList("A", "B"));
                        }
                    }
                }
            }
        }
        
        return result;
    }

    @Override
    @Transactional
    public ApiResponse<?> importQuestions(List<QuestionRequest> questions) {
        if (questions == null || questions.isEmpty()) {
            return ApiResponse.error("没有可导入的试题");
        }
        
        int successCount = 0;
        StringBuilder errorMessages = new StringBuilder();
        
        for (int i = 0; i < questions.size(); i++) {
            try {
                ApiResponse<?> response = addQuestion(questions.get(i));
                if (response.isSuccess()) {
                    successCount++;
                } else {
                    errorMessages.append("第").append(i + 1).append("题导入失败: ").append(response.getMessage()).append("\n");
                }
            } catch (Exception e) {
                errorMessages.append("第").append(i + 1).append("题导入异常: ").append(e.getMessage()).append("\n");
            }
        }
        
        if (errorMessages.length() > 0) {
            return ApiResponse.error("部分试题导入失败\n" + errorMessages.toString());
        }
        
        return ApiResponse.success("成功导入" + successCount + "道试题", null);
    }
    
    // 辅助方法：验证试题类型是否有效
    private boolean isValidQuestionType(String type) {
        return type != null && (
            "MULTIPLE_CHOICE".equals(type) ||
            "SINGLE_CHOICE".equals(type) ||
            "TRUE_FALSE".equals(type) ||
            "FILL_BLANK".equals(type) ||
            "SHORT_ANSWER".equals(type)
        );
    }
} 